package com.keensense.vcm.common.auth;

/**
 * @author lanjian
 * @date 2020/4/29
 */
public class DefaultCredentialProvider implements CredentialsProvider {

    private volatile Credentials creds;

    public DefaultCredentialProvider(String userName, String password) {
        this(userName, password, null);
    }

    public DefaultCredentialProvider(Credentials creds) {
        setCredentials(creds);
    }

    public DefaultCredentialProvider(String userName, String password, String cookies) {
        checkCredentials(userName, password);
        setCredentials(new DefaultCredentials(userName, password, cookies));
    }

    @Override
    public synchronized void setCredentials(Credentials creds) {
        if (creds == null) {
            throw new InvalidCredentialsException("creds should not be null.");
        }

        checkCredentials(creds.getUserName(), creds.getPassword());
        this.creds = creds;
    }

    @Override
    public Credentials getCredentials() {
        if (this.creds == null) {
            throw new InvalidCredentialsException("Invalid credentials");
        }

        return this.creds;
    }

    private static void checkCredentials(String userName, String password) {
        if (userName == null || userName.equals("")) {
            throw new InvalidCredentialsException("Access key id should not be null or empty.");
        }

        if (password == null || password.equals("")) {
            throw new InvalidCredentialsException("Secret access key should not be null or empty.");
        }
    }

}
